package com.zxp.pstationapk.view;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.daimajia.numberprogressbar.NumberProgressBar;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBar;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zxp.pstationapk.R;
import com.zxp.pstationapk.base.Constant;
import com.zxp.pstationapk.bean.PstationRouteModel;
import com.zxp.pstationapk.fastjson.FastJsonConverterFactory;
import com.zxp.pstationapk.retrofit.ApiService;
import com.zxp.pstationapk.retrofit.ProgressHandler;
import com.zxp.pstationapk.retrofit.ProgressHelper;
import com.zxp.pstationapk.util.CheckFileisExitTool;
import com.zxp.pstationapk.util.NetUtils;
import com.zxp.pstationapk.util.ToastTool;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;


/**
 * @author Created by zxp on 2018/5/22.
 *         function:线路展示
 *         添加线路数据
 *         下载线路图片
 */

public class RouteActivity extends AppCompatActivity implements PopupWindow.OnDismissListener {
    @BindView(R.id.topbar_pstation)
    QMUITopBar topbarPstation;
    @BindView(R.id.rv_station_route)
    RecyclerView routeStationRv;

    private String[] nameData = null;
    private static final String TAG = "RouteActivity";
    private String titleTv = null;
    private SparseBooleanArray isDownLoadList;
    List<PstationRouteModel> pstationRouteModelList;
    private PopupWindow popupWindow;

    private Dialog mDownloadDialog;
    private NumberProgressBar numberProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route);
        QMUIStatusBarHelper.translucent(this);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        Intent intent = getIntent();
        titleTv = intent.getStringExtra("stationTitle");
        topbarPstation.setTitle(titleTv);
        topbarPstation.setBackgroundAlpha(130);

        if (titleTv.equals(Constant.pstion_Data_110kv[0])) {
            nameData = Constant.pstation_route_daoguan;
        } else if (titleTv.equals(Constant.pstion_Data_110kv[1])) {
            nameData = Constant.pstation_route_rongjiang;
        } else if (titleTv.equals(Constant.pstion_Data_110kv[2])) {
            nameData = Constant.pstation_route_yuanhe;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[0])) {
            nameData = Constant.pstation_route_huangnipo;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[1])) {
            nameData = Constant.pstation_route_gaoshang;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[2])) {
            nameData = Constant.pstation_route_qianxiang;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[3])) {
            nameData = Constant.pstation_route_chetian;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[4])) {
            nameData = Constant.pstation_route_jinshi;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[5])) {
            nameData = Constant.pstation_route_shanglin;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[6])) {
            nameData = Constant.pstation_route_yanguan;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[7])) {
            nameData = Constant.pstation_route_mochuan;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[8])) {
            nameData = Constant.pstation_route_baishi;
        } else if (titleTv.equals(Constant.pstion_Data_35kv[9])) {
            nameData = Constant.pstation_route_jieshou;
        } else if (titleTv.equals(Constant.pstion_Data_10kv[0])) {
            nameData = Constant.pstation_route_xiayunqiao;
        }

        checkFileExit();
        initEvent();
    }

    private void checkFileExit() {
        isDownLoadList = new SparseBooleanArray();
        pstationRouteModelList = new ArrayList();
        for (int i = 0; i < nameData.length; i++) {
            PstationRouteModel model = new PstationRouteModel();
            if (CheckFileisExitTool.check("///" + "storage/emulated/0/" + nameData[i] + ".jpg")) {
                isDownLoadList.put(i, true);
            } else {
                isDownLoadList.put(i, false);
            }
            model.setName(nameData[i]);
            model.setDownLoad(isDownLoadList.get(i));
            pstationRouteModelList.add(model);
        }

        initAdapter();
    }

    //初始化适配器
    private void initAdapter() {
        routeStationRv.setLayoutManager(new LinearLayoutManager(this));
        routeStationRv.setItemAnimator(new DefaultItemAnimator());
        routeStationRv.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration
                .VERTICAL_LIST));
        routeStationRv.setAdapter(new CommonAdapter<PstationRouteModel>(this, R.layout
                .rv_item_route, pstationRouteModelList) {

            @Override
            protected void convert(ViewHolder holder, PstationRouteModel pstationRouteModel, int
                    position) {
                final String name = pstationRouteModelList.get(position).getName();
                boolean isDownLoad = pstationRouteModelList.get(position).isDownLoad();
                if (name != null) {
                    holder.setText(R.id.tv_route_name, name);
                }

                if (isDownLoad) {
                    holder.setText(R.id.tv_download_text, "下载完成");
                } else {
                    holder.setText(R.id.tv_download_text, "未下载");
                }

                holder.setOnClickListener(R.id.rl_content, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(RouteActivity.this, LargeImageViewActivity
                                .class);
                        intent.putExtra("stationName", name);
                        startActivity(intent);
                    }
                });
            }
        });
    }

    private void initEvent() {
        topbarPstation.addRightTextButton("下载", R.id.topbar_right_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (NetUtils.isNetworkConnected(RouteActivity.this)) {
                    setUpDownLoadDialog();
                } else {
                    ToastTool.show("当前网络连接不通畅，请手动打开网络连接");
                }
            }
        });
    }

    private void setUpDownLoadDialog() {
        ToastTool.show("图纸正在下载中");
        String localStr = Environment.getExternalStorageDirectory().getAbsolutePath();
        Log.e(TAG, "下载地址===>" + localStr);
        downLoadMorePng(nameData);
        mDownloadDialog = new Dialog(this, R.style.Theme_AppCompat_Dialog_Alert);
        View view = getLayoutInflater().inflate(R.layout.progress_dialog, null);
        numberProgressBar = (NumberProgressBar) view.findViewById(R.id.number_progress_bar);
        mDownloadDialog.setContentView(view);
        mDownloadDialog.show();
    }

    /**
     * 启动下载
     *
     * @param nameData
     */
    private void downLoadMorePng(final String[] nameData) {
        Retrofit.Builder retrofitBuilder = new Retrofit.Builder().addConverterFactory
                (FastJsonConverterFactory.create()).baseUrl(Constant.baseUrl);
        OkHttpClient.Builder builder = ProgressHelper.addProgress(null);
        ApiService retrofit = retrofitBuilder.client(builder.build()).build().create(ApiService
                .class);
        for (final String s : nameData) {
            String downloadUrl = s + Constant.pdf_load_url_end_jpg;
            Call<ResponseBody> call = retrofit.downLoadImage(downloadUrl);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    if (response.isSuccessful()) {
                        saveImageFile(response.body(), s);
                        if (mDownloadDialog != null && mDownloadDialog.isShowing()) {
                            mDownloadDialog.dismiss();
                        }
                        checkFileExit();
                    }
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }
            });
        }

        ProgressHelper.setProgressHandler(new ProgressHandler() {
            @Override
            protected void onProgress(long progress, long total, long speed, boolean done) {
                numberProgressBar.setProgress((int) (progress / 1024));
            }
        });
    }

    /**
     * 保存文件到本地
     *
     * @param body
     * @param s
     */
    private void saveImageFile(ResponseBody body, String s) {
        try {
            File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = new File(dir, s + ".jpg");
            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];
                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(file);

                while (true) {
                    int read = inputStream.read(fileReader);
                    if (read == -1) {
                        break;
                    }
                    outputStream.write(fileReader, 0, read);
                    fileSizeDownloaded += read;
                    Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
                }

                outputStream.flush();
            } catch (IOException e) {
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
        }
    }

    @Override
    public void onDismiss() {
        backgroundAlpha(1.0f);
    }

    private void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        //0.0-1.0
        lp.alpha = bgAlpha;
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkFileExit();
    }
}
